#include "util/Locale.h"
#include <clocale>
#include <cstdlib>
#include <locale>
#include <memory>
#include <string>
using namespace yzrilyzr_lang;
namespace yzrilyzr_util{
	namespace Locales{
		const std::shared_ptr<Locale> SIMPLIFIED_CHINESE=std::make_shared<Locale>("zh", "CN");
		const std::shared_ptr<Locale> ENGLISH=std::make_shared<Locale>("en", "");
		const std::shared_ptr<Locale> US=std::make_shared<Locale>("en", "US");
	}

	Locale::Locale(){
		const char * langEnv=std::getenv("LANG");
		if(langEnv){
			String langStr(langEnv);
			u_index underPos=langStr.indexOf('_');
			u_index dotPos=langStr.indexOf('.');
			if(underPos != -1){
				language=langStr.substring(0, underPos);
				country=langStr.substring(underPos + 1,
										  (dotPos != -1?dotPos:langStr.length()) - underPos - 1);
			}
		}
		if(language.empty()) language="en";
		if(country.empty()) country="US";
	}
	Locale::Locale(const String & language, const String & country, const String & variant)
		: language(language), country(country), variant(variant){}
	Locale::Locale(const String & language, const String & country)
		: language(language), country(country), variant(""){}

	String Locale::toString() const{
		return language + "_" + country + (variant.empty()?"":("_" + variant));
	}
	bool Locale::operator==(const Locale & other) const noexcept{
		return language == other.language && country == other.country && variant == other.variant;
	}
	bool Locale::operator!=(const Locale & other) const noexcept{
		return !(*this == other);
	}
	std::shared_ptr<Locale> Locale::getDefault(){
		return Locales::SIMPLIFIED_CHINESE;
	}
}